# import bcrypt
import json

from flask import jsonify
from sqlalchemy import inspect
from routes import app, db
from utils.redis import redis_client_instance


@app.route('/')
def hello_world():  # put application's code here
    return '铅山县GEP项目的后端数据服务 !'


# 在 routes/homepage_router.py 中添加
@app.route("/redis_test", methods=['GET'])
def redis_test():
    try:
        # 测试基本操作
        test_key = "test_key"
        test_value = {"message": "Hello Redis", "测试": "中文测试"}

        # 设置测试数据
        success = redis_client_instance.setex(test_key, 60, json.dumps(test_value))

        if success:
            # 获取测试数据
            cached_data = redis_client_instance.get(test_key)
            if cached_data:
                parsed_data = json.loads(cached_data)
                return jsonify({
                    "status": "success",
                    "set_success": True,
                    "get_success": True,
                    "data": parsed_data
                })
            else:
                return jsonify({
                    "status": "partial_success",
                    "set_success": True,
                    "get_success": False,
                    "message": "Data was set but could not be retrieved"
                })
        else:
            return jsonify({
                "status": "error",
                "set_success": False,
                "message": "Failed to set data in Redis"
            })

    except Exception as e:
        return jsonify({
            "status": "error",
            "message": str(e)
        }), 500

@app.route("/redis_test/clear", methods=['DELETE'])
def clear_redis_test_data():
    try:
        # 要删除的测试键
        test_key = "test_key"

        # 从Redis中删除测试数据
        deleted_count = redis_client_instance.delete(test_key)

        if deleted_count > 0:
            return jsonify({
                "status": "success",
                "message": f"Successfully deleted test data with key '{test_key}'",
                "deleted_count": deleted_count
            })
        else:
            return jsonify({
                "status": "info",
                "message": f"No data found for key '{test_key}' or already deleted",
                "deleted_count": 0
            })

    except Exception as e:
        return jsonify({
            "status": "error",
            "message": str(e)
        }), 500


# 添加 Redis 状态检查端点
@app.route("/redis_status", methods=['GET'])
def redis_status():
    try:
        if redis_client_instance.client:
            # 尝试 ping Redis 服务器
            redis_client_instance.client.ping()
            return jsonify({
                "status": "connected",
                "message": "Redis is properly connected"
            })
        else:
            return jsonify({
                "status": "not_initialized",
                "message": "Redis client is not initialized"
            })
    except Exception as e:
        return jsonify({
            "status": "error",
            "message": f"Redis connection error: {str(e)}"
        }), 500

def init_db():
    with app.app_context():
        inspector = inspect(db.engine)
        if not inspector.has_table('users'):
            from models.user_model import User
            db.create_all()
            # password_hashed = bcrypt.hashpw('123456'.encode(), bcrypt.gensalt())
            user = User(username="root", password='123456',email="<EMAIL>")
            db.session.add(user)
            db.session.commit()


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8123)
